package com.springcloud.redis.jhs.service;

import cn.hutool.core.date.DateUtil;
import com.springcloud.redis.jhs.constants.Constants;
import com.springcloud.redis.jhs.entities.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author liyanhao
 * @Date 2022-11-24 21:49
 */
@Slf4j
@Service
public class JHSTaskService {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void initJHS() {
        log.info("启动定时器淘宝聚划算功能模拟....." + DateUtil.now());
        new Thread(() -> {
            //模拟定时器，定时把数据库的特价商品，刷新到redis中
            while (true) {
                //模拟从数据库读取100件特价商品，用于加载到聚划算的页面中
                List<Product> list = this.products();
                //采用redis的list数据结构进存数据
//                redisTemplate.opsForList().leftPushAll(Constants.JHS_KEY, list);
                //先更新b缓存 有效20天
                redisTemplate.delete(Constants.JHS_KEY_B);
                redisTemplate.opsForList().leftPushAll(Constants.JHS_KEY_B, list);
                redisTemplate.expire(Constants.JHS_KEY_B, 20L, TimeUnit.DAYS);
                //再更新A缓存 有效15天 差异化有效时间
                redisTemplate.delete(Constants.JHS_KEY_A);
                redisTemplate.opsForList().leftPushAll(Constants.JHS_KEY_A, list);
                redisTemplate.expire(Constants.JHS_KEY_A, 15L, TimeUnit.MILLISECONDS);
                //间隔一分钟执行一遍
                try {
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                log.info("runjhs定时刷新.....");

            }
        }, "t1").start();
    }

    //模拟从数据库读取100件特价商品，用于加载到聚划算的页面中
    public List<Product> products() {
        ArrayList<Product> list = new ArrayList<>();
        for (int i = 0; i <= 20; i++) {
            Random random = new Random();
            int id = random.nextInt(10000);
            Product product = new Product(Long.valueOf(i), "Product" + i, i, "detail");
            list.add(product);
        }
        return list;
    }
}
